import axios from 'axios'
// element组件库提供消息提示组件
import { Message } from 'element-ui'
// 导入vuex实例
import store from '@/store'
// import { getToken } from '@/utils/auth'
import router from '@/router/index.js'
// create an axios instance
const service = axios.create({
  // 动态配置请求的url=>开发环境和生产环境请求地址是不一样的
  baseURL: process.env.VUE_APP_BASE_API, // url = base url + request url
  // withCredentials: true, // send cookies when cross-domain requests
  timeout: 5000 // request timeout
})

// request interceptor
// 请求拦截器=>请求还没有发出去
// 统一想header中统一添加token
service.interceptors.request.use(
  config => {
    // do something before request is sent

    if (store.getters.token) {
      // let each request carry token
      // ['X-Token'] is a custom headers key
      // please modify it according to the actual situation
      config.headers.Authorization = `Bearer ${store.getters.token}`
    }
    return config
  },
  error => {
    // do something with request error
    console.log(error) // for debug
    return Promise.reject(error)
  }
)

// response interceptor
// 响应拦截器=>已经获取到数据了
service.interceptors.response.use(

  response => {
    // 请求成功进入这里
    const { data, success, message } = response.data
    console.log('响应:', response)
    if (success) {
      return data
    } else {
      Message({
        message,
        type: 'error',
        duration: 3 * 1000
      })
      return Promise.reject(new Error(message || 'Error'))
    }
  },
  error => {
    // 请求失败执行这里
    console.dir(error) // for debug
    if (error.response && error.response.status === 401) {
      if (router.currentRoute.path === '/login') return
      store.dispatch('user/logoutAction')
      router.replace(`/login?redirect=${router.currentRoute.fullPath}`)
    }
    // 错误信息提示
    Message({
      message: error.response.data.message,
      type: 'error',
      duration: 3 * 1000
    })
    // this.$router.replace('/login')

    // 中断promise并抛出错误提示
    return Promise.reject(error)
  }
)

export default service
